package com.guchenbo.example.tool;

import cn.hutool.core.io.FileUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.List;

public class XunLeiTool {
    protected static final Logger log = LoggerFactory.getLogger(XunLeiTool.class);

    public static void main(String[] args) throws Exception {
        String baseDir = "/Users/guchenbo/Downloads/xunlei";
        String origin = "d球m动d3j";
        String target = "地球脉动 第三季";
        rename(baseDir, origin, target);
    }

    private static void rename(String baseDir, String origin, String target) throws Exception {
        File dir = new File(baseDir);
        if (dir.exists() && dir.isDirectory()) {
            String destDir = baseDir + File.separator + target;
            File destDirFile = new File(destDir);
            if (!destDirFile.exists()) {
                destDirFile.mkdirs();
            }
            List<File> files = new ArrayList<>();
            loopFiles(dir, files, pathname -> pathname.getName().contains(origin));
            files.forEach(f -> {
                String o = f.getName();
                o = StringUtils.substringAfter(o, origin);
                File n = new File(destDir, target + o);
                log.info("move file {} to {}", f.getAbsolutePath(), n.getAbsolutePath());
                FileUtil.rename(f, n.getAbsolutePath(), false);
            });
        } else {
            throw new Exception("not dir");
        }
    }

    private static void loopFiles(File dir, List<File> files, FileFilter filter) {
        if (!dir.exists()) {
            return;
        }
        if (dir.isDirectory()) {
            File[] fs = dir.listFiles(filter);
            for (File f : fs) {
                if (f.isDirectory()) {
                    loopFiles(f, files, filter);
                } else if (f.isFile()) {
                    if (filter != null && filter.accept(f)) {
                        files.add(f);
                    }
                }
            }
        }
    }
}
